package com.graduation_design.modules.system.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.graduation_design.common.lang.Result;
import com.graduation_design.entity.SysRole;
import com.graduation_design.entity.SysUser;
import com.graduation_design.modules.app.controller.BaseController;
import com.graduation_design.service.SysRoleService;
import com.graduation_design.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends BaseController {

    @Resource
    SysUserService sysUserService;

    @Resource
    SysRoleService sysRoleService;

    /**
     * 获取管理员列表
     */
    @GetMapping("/list")
    @RequiresPermissions("sys:user:list")
    public Result page(SysUser sysUser) {
        return Result.success(sysUserService.getPage(getPage(), sysUser));
    }

    /**
     * 给管理员分配角色的时候需要把原先对应的角色信息查出来
     */
    @GetMapping("/info/{id}")
    @RequiresPermissions("sys:user:list")
    public Result info(@PathVariable Long id) {
        SysUser user = sysUserService.getById(id);
        Assert.notNull(user, "找不到该管理员！");

        List<SysRole> roles = sysRoleService.listRolesByUserId(user.getId());
        user.setRoles(roles);

        return Result.success(user);
    }

    /**
     * 新增管理员时候设置默认密码，编辑的时候有密码重新设置密码，没有密码则跳过
     */
    @PostMapping("/save")
    @RequiresPermissions(value = {"sys:user:save", "sys:user:update"}, logical = Logical.OR)
    public Result save(@Validated @RequestBody SysUser sysUser) {
        if (sysUser.getId() == null) {
            sysUser.setCreated(LocalDateTime.now());
            sysUser.setAvatar("https://image-1300566513.cos.ap-guangzhou.myqcloud.com/upload/zhuawaba/5a9f48118166308daba8b6da7e466aab.jpg");
        } else {
            sysUser.setUpdated(LocalDateTime.now());

            SysUser temp = sysUserService.getById(sysUser.getId());
            BeanUtil.copyProperties(sysUser, temp, "password", "created", "updated");

            // 密码不为空时候更新密码
            if (StrUtil.isNotBlank(sysUser.getPassword())) {
                temp.setPassword(SecureUtil.md5(sysUser.getPassword()));
            }
        }

        sysUserService.saveOrUpdate(sysUser);
        return Result.success(sysUser);
    }

    /**
     * 删除管理员
     */
    @PostMapping("/delete")
    @RequiresPermissions("sys:user:delete")
    public Result delete(@RequestBody Long[] ids) {

        sysUserService.deleteBath(ids);
        return Result.success();
    }

    /**
     * 分配角色
     */
    @PostMapping("/role/{userId}")
    @RequiresPermissions("sys:user:role")
    public Result setRole(@PathVariable Long userId, @RequestBody Long[] roleIds) {

        log.info("设置roleIds -- > {}", roleIds);

        sysUserService.setRole(userId, roleIds);
        return Result.success();
    }

    /**
     * 超级管理员重置密码
     */
    @PostMapping("/resetPwd")
    @RequiresPermissions("sys:user:resetPwd")
    public Result resetPwd(Long userId) {

        SysUser sysUser = sysUserService.getById(userId);
        sysUser.setPassword(SecureUtil.md5("888888"));
        sysUser.setUpdated(LocalDateTime.now());
        sysUserService.updateById(sysUser);
        return Result.success();
    }


}
